#include <iostream>
#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/TcpServer.h>
#include <muduo/net/Buffer.h>
#include <muduo/base/CountDownLatch.h>
#include <string>
#include <unordered_map>


class Dictclient
{
public:
    Dictclient(const std::string sip,int sport)
    :_client(_eve_loop,muduo::net::InetAddress(sip,sport),"DictClient"),
    _eve_loop(_loopthread.startLoop()),
    _downlatch(1)
    {
        //获取非静态成员函数的地址时，必须显式指定类名
        _client.setConnectionCallback(std::bind(&Dictclient::OnConnection,this,std::placeholders::_1));
        _client.setMessageCallback(std::bind(&Dictclient::OnMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));

        _client.connect();
        _downlatch.wait();
    }
    bool send(const std::string& msg)
    {
        if(!_conn->connected())
        {
            std::cout << "连接已经断开" << std::endl;
            return false;
        }
        _conn->send(msg);
        return true;
    }
private:
    //设置回调函数
    void OnMessage(const muduo::net::TcpConnectionPtr& conn,muduo::net::Buffer* buffer,muduo::Timestamp timestamp)
    {
        std::string res = buffer->retrieveAllAsString();
        std::cout << res << std::endl;
    }
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected())
        {
            std::cout << "建立连接成功" << std::endl;
            _downlatch.countDown();//可能连接还没有建立成功，就send，所以需要加计数器
            _conn = conn;
        }
        else
        {
            std::cout << "连接断开" << std::endl;
            _conn.reset();
        }
    }
private:
    muduo::net::EventLoopThread _loopthread;
    muduo::net::EventLoop* _eve_loop;
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _downlatch;//计数器。计数为0时候被唤醒
};

int main()
{
    Dictclient client("127.0.0.1",9090);
    while(true){
        std::string msg;
        std::cin >> msg;
        client.send(msg);
    }
    return 0;
}